package com.erp.ae.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.ae.domain.ImageBankParam;
import com.erp.ae.service.IAeProductService;
import com.global.iop.domain.Protocol;
import com.ruoyi.ae.api.domain.AeProductPost;
import com.ruoyi.gather.api.RemoteCollectProductSkuService;
import com.ruoyi.gather.api.RemoteSellerProductService;
import com.ruoyi.gather.api.domain.dto.AeAutoProductDto;
import com.ruoyi.common.core.domain.R;
import com.erp.ae.utils.AeApiUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import java.util.*;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/erp/erpProduct")
public class AeProductController extends BaseController {

    private final IAeProductService iAeProductService;
    private final RemoteCollectProductSkuService remoteCollectProductSkuService;

    /**
     * 获取类目权限
     */
    @GetMapping("/categoryTreeList")
    public String categoryTreeList(@RequestParam("categoryId") String categoryId, @RequestParam("sellerId") Long sellerId) {
        return iAeProductService.categoryTreeList(categoryId, sellerId);

    }

    /**
     * 获取类目权限
     */
    @GetMapping("/categoryTreeListInnerAuth/{categoryId}/{sellerId}")
    public String categoryTreeListInnerAuth(@PathVariable("categoryId") String categoryId, @PathVariable("sellerId") Long sellerId) {
        return iAeProductService.categoryTreeList(categoryId, sellerId);
    }

    /**
     * 获取类目品牌
     */
    @GetMapping("/storeBrandsList")
    public R<Object> storeBrandsList(@RequestParam("categoryId") String categoryId, @RequestParam("storeId") Long storeId) {
        //生成参数Map
        return iAeProductService.storeBrandsList(categoryId, storeId);
    }

    /**
     * 下架商品
     */
    @PostMapping("/offlineAeProduct")
    public R<Object> offlineAeProduct(@RequestBody Map<String, Object> paremeterMap) {
        return iAeProductService.offlineAeProduct(paremeterMap);
    }

    /**
     * 上架商品
     */
    @PostMapping("/onlineaeproduct")
    public R<Object> onlineaeproduct(@RequestBody Map<String, Object> paremeterMap) {
        return iAeProductService.onlineaeproduct(paremeterMap);
    }

    /**
     * 上传至图片银行
     *
     * @return
     */
    @PostMapping("/uploadImageForSDKTest")
    public R<Object> uploadImageForSDK(
            @RequestBody ImageBankParam imageBankParam
    ) {
        ImageBankParam imageBankParam1 = iAeProductService.uploadImageForSDK(imageBankParam);
        if (ObjectUtils.isNotNull(imageBankParam1)) {
            return R.ok(imageBankParam1);
        } else {
            return R.fail();
        }
    }

    /**
     * 测试发布上传
     *
     * @param map
     * @return
     */
    @PostMapping("/uploadProductTest")
    public R<Object> uploadProductTest(@RequestBody Map<String, Object> map) {
        return iAeProductService.uploadProductTest(map);
    }

    /**
     * 获取欧盟负责人
     *
     * @return
     */
    @GetMapping("/getEUResponsiblePersonFromAe")
    public Map<String, Object> getEUResponsiblePersonFromAe(@RequestParam("categoryId") Long categoryId, @RequestParam("sellerId") Long sellerId) {
        return iAeProductService.getEUResponsiblePersonFromAe(categoryId, sellerId);
    }

    /**
     * 获取欧盟负责人
     *
     * @return
     */
    @GetMapping("/getEUResponsiblePersonFromAeInnerAuth/{categoryId}/{storeId}")
    public R<Object> getEUResponsiblePersonFromAeInnerAuth(@PathVariable("categoryId") Long categoryId, @PathVariable("storeId") Long storeId) {
        return R.ok(iAeProductService.getEUResponsiblePersonFromAe(categoryId, storeId));
    }


    /**
     * 获取服务模板
     *
     * @return
     */
    @GetMapping("/queryPromiseTemplateById/{templateId}/{storeId}")
    public R<Object> queryPromiseTemplateById(@RequestParam("templateId") String templateId, @RequestParam("storeId") Long storeId) {
        return iAeProductService.queryPromiseTemplateById(Integer.parseInt(templateId), storeId);
    }

    /**
     * 获取平台运费模板 物流发货地国家
     */
    @PostMapping("/getFreightTemplateLogisticsCompany")
    public R<Object> getFreightTemplateLogisticsCompany(
            @RequestBody Map<String, Object> map
    ) throws Exception {
        return iAeProductService.getFreightTemplateLogisticsCompany(map);
    }

    /**
     * 获取平台运费模板 物流发货地国家
     */
    @GetMapping("/getFreightTemplateLogisticsCompany/{templateId}/{storeId}")
    R<Object> getFreightTemplateLogisticsCompany(@PathVariable("templateId") Long templateId, @PathVariable("storeId") Long storeId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("storeId", storeId);
        map.put("templateId", templateId);
        return iAeProductService.getFreightTemplateLogisticsCompany(map);
    }

    /**
     * 获取店铺运费模板
     */
    @GetMapping("/getSellerStoreFreightTemplate/{sellerId}")
    R<Object> getSellerStoreFreightTemplate(@PathVariable("sellerId") Long sellerId) throws Exception {
        return iAeProductService.getSellerStoreFreightTemplate(sellerId);
    }


    /**
     * 查询速卖通商品详情
     *
     * @param productId
     * @param sellerId
     * @return
     */
    @GetMapping("/queryAeProduct")
    public R<Object> queryAeProduct(Long productId, String sellerId) {
        return iAeProductService.queryAeProduct(productId, sellerId);
    }

    /**
     * 查询速卖通商品详情
     *
     * @param productId
     * @param sellerId
     * @return
     */
    @GetMapping("/queryAeProductInnerAuth/{productId}/{sellerId}")
    public R<Object> queryAeProductInnerAuth(@PathVariable("productId") Long productId, @PathVariable("sellerId") String sellerId) {
        return iAeProductService.queryAeProduct(productId, sellerId);
    }

    /**
     * 获取商品信息
     */
    @PostMapping("/findAeProductById")
    public R<Object> findAeProductById(@RequestBody Map<String, Object> map) {
        return iAeProductService.findAeProductById(map);
    }

    /**
     * 根据发布类目id、父属性路径（可选）获取子属性信息 )
     *
     * @param param1
     * @param sellerId
     * @return
     */
    @GetMapping("/getchildattributesresultbypostcateidandpath")
    public R<Object> getchildattributesresultbypostcateidandpath(String param1, String sellerId) {
        return iAeProductService.getchildattributesresultbypostcateidandpath(param1, sellerId);
    }


    /**
     * 修改商品
     */
    @PostMapping("/productEdit")
    public R<Object> productEdit(@RequestBody AeProductPost aeProductPost) {
        return iAeProductService.productEdit(aeProductPost);
    }

    /**
     * 查询商品审核状态
     */
    @GetMapping("/findAeProductStatusById/{aeProductId}/{storeId}")
    public R<Object> findaeproductstatusbyid(@PathVariable("aeProductId") Long aeProductId, @PathVariable("storeId") Long storeId) {
        return iAeProductService.findAeProductStatusById(aeProductId, storeId);
    }


    /**
     * 获取类目资质信息
     */
    @GetMapping("/queryCategoryQualificationList")
    public R<Object> queryCategoryQualificationList(Long categoryId, Long sellerId) {
        return iAeProductService.queryCategoryQualificationList(categoryId, sellerId);

    }


    /**
     * 编辑商品的单个字段
     *
     * @param map
     * @return
     */

    @PostMapping("/editSimpleProductFiled")
    public R<Object> editSimpleProductFiled(@RequestBody Map<String, Object> map) {
        return iAeProductService.editSimpleProductFiled(map);
    }

    /**
     * 商品编辑 jsonObject版
     */
    @PostMapping("/editProductByAeData")
    public R<Object> editProductByAeData(@RequestBody Map<String, Object> map) {
        String accessToken = AeApiUtils.getToken((String) map.get("storeId"));
        String productDataStr = (String) map.get("productData");
        JSONObject productData = JSONObject.parseObject(productDataStr);

        Map<String, Object> productMap = new HashMap<>();
        productMap.put("gmt_create", productData.get("gmt_create"));
        productMap.put("lot_num", productData.get("lot_num"));

        String productPropertys = productData.getString("aeop_ae_product_propertys");
        JSONArray propertyList = new JSONArray();
        if (productPropertys.contains("aeop_ae_product_property")) {
            propertyList = JSONArray.parseArray(productData.getJSONObject("aeop_ae_product_propertys").getString("aeop_ae_product_property"));
        } else {
            propertyList = JSONArray.parseArray(productData.getString("aeop_ae_product_propertys"));
        }
        productMap.put("aeop_ae_product_propertys", propertyList);

        productMap.put("ws_valid_num", productData.get("ws_valid_num"));
        productMap.put("delivery_time", productData.get("delivery_time"));
        productMap.put("product_status_type", productData.get("product_status_type"));
        productMap.put("package_type", productData.get("package_type"));
        productMap.put("gmt_modified", productData.get("gmt_modified"));
        productMap.put("detail_source_list", productData.getJSONObject("detail_source_list").get("detail_source"));
        productMap.put("locale", productData.get("locale"));
        productMap.put("currency_code", productData.get("currency_code"));
        productMap.put("package_height", productData.get("package_height"));

        if (ObjectUtils.isNotNull(productData.get("aeop_a_e_multimedia"))) {
            productMap.put("aeop_a_e_multimedia", productData.get("aeop_a_e_multimedia"));
        }
        productMap.put("package_height", productData.get("package_height"));

        JSONArray skuList = JSONArray.parseArray(productData.getJSONObject("aeop_ae_product_s_k_us").getString("aeop_ae_product_sku"));
        for (int i = 0; i < skuList.size(); i++) {
            JSONObject sku = skuList.getJSONObject(i);
            String aeopSkuProperty = sku.getJSONObject("aeop_s_k_u_property_list").getString("aeop_sku_property");
            JSONObject aeopSkuPropertyObject = JSONObject.parseObject(aeopSkuProperty);
            sku.remove("aeop_s_k_u_property_list");
            sku.put("aeop_s_k_u_property", JSONArray.parseArray(aeopSkuProperty));
            System.out.println(sku);
        }
        productMap.put("aeop_ae_product_s_k_us", skuList);

        productMap.put("category_id", productData.get("category_id"));
        productMap.put("subject_list", productData.getJSONObject("subject_list").get("subject"));
        productMap.put("image_u_r_ls", productData.get("image_u_r_ls"));
        productMap.put("package_length", productData.get("package_length"));
        productMap.put("product_id", productData.get("product_id"));
        productMap.put("reduce_strategy", productData.get("reduce_strategy"));
//        productMap.put("reduce_strategy", "place_order_withhold");
        productMap.put("gross_weight", productData.get("gross_weight"));
        productMap.put("freight_template_id", productData.get("freight_template_id"));
        productMap.put("promise_template_id", productData.get("promise_template_id"));
        productMap.put("msr_eu_id", productData.get("msr_eu_id"));
        productMap.put("aeop_qualification_struct_list", productData.get("aeop_qualification_struct_list"));
        productMap.put("product_unit", productData.get("product_unit"));
        productMap.put("package_width", productData.get("package_width"));

        String marketImages = productData.getString("market_images");
        if (ObjectUtils.isNotEmpty(marketImages)) {
            if (marketImages.contains("market_image")) {
                productMap.put("market_images", productData.getJSONObject("market_images").get("market_image"));
            } else {
                productMap.put("market_images", productData.get("market_images"));
            }
        }

        HashMap<String, Object> extParamMap = new HashMap<>();
        extParamMap.put("edit_reason", "edit_by_isv");
        map.put("ext_param", extParamMap);

        JSONObject json = new JSONObject(productMap);
        System.out.println(json);
        Map<String, Object> paremeterMap = new HashMap<>();
        paremeterMap.put("aeop_a_e_product", json);

        System.out.println("****************************************************");

        System.out.println(paremeterMap);

        String msg =
                AeApiUtils.sendRequest(
                        "aliexpress.offer.product.edit",
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);

        return R.ok(msg);
    }

    /**
     * 查看店铺商品异常信息
     *
     * @param map
     * @return
     */
    @PostMapping("/pageQueryProblem")
    public R<Object> pageQueryProblem(@RequestBody Map<String, Object> map) {
        return iAeProductService.pageQueryProblem(map);

    }

    /**
     * 商品发布/商品上传
     *
     * @param aeProductPost
     * @return
     */
    @PostMapping("/getErpProductInfo")
    public R<Object> getErpProductInfo(@RequestBody AeProductPost aeProductPost) {
        return iAeProductService.getErpProductInfo(aeProductPost);
    }

    /**
     * 自动化商品发布/商品上传
     *
     * @return
     */
    @PostMapping("/autoPublishToAe")
    public R<Object> autoPublishToAe(@RequestBody AeAutoProductDto aeAutoProductDto) {
        return iAeProductService.autoPublishToAe(aeAutoProductDto);
    }

    /**
     * ae商品下架（旧版）
     *
     * @return
     */
    @PostMapping("/productOfflineForUpdateTestInnerAuth")
    public R<Object> productOfflineForUpdateTestInnerAuth(@RequestBody Map<String, Object> map) {
        String aeProductIds = (String) map.get("aeProductIds");
        Long storeId = (Long) map.get("storeId");
        Integer type = (Integer) map.get("type");
        return iAeProductService.productOfflineForUpdateTest(aeProductIds, storeId, type);
    }

    /**
     * ae商品下架（新版）
     *
     * @return
     */
    @GetMapping("/productOffline/{aeProductId}/{storeId}")
    public R<Object> productOffline(@PathVariable("aeProductId") Long aeProductId, @PathVariable("storeId") Long storeId) {
        return iAeProductService.productOffline(aeProductId, storeId);
    }

    /**
     * ae商品删除
     *
     * @return
     */
    @GetMapping("/deleteProductToAe/{aeProductId}/{storeId}")
    public R<Object> deleteProductToAe(@PathVariable("aeProductId") Long aeProductId, @PathVariable("storeId") Long storeId) {
        return iAeProductService.deleteProduct(aeProductId, storeId);
    }

}
